package com.shxy.controller;

import com.shxy.common.entity.JsonResult;
import com.shxy.common.enums.ResultCode;
import com.shxy.common.utils.ResultTool;
import com.shxy.controller.ui.news.NewsItem;
import com.shxy.controller.ui.news.NewsBase;
import com.shxy.entity.wlzx.News;
import com.shxy.service.INewsService;
import com.shxy.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/news")
public class NewsController {
    @Autowired
    private INewsService newsService;
    @Autowired
    private IUserService userService;
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 根据通知消息
     * @return
     */
    @GetMapping("/info/{id}")
    public JsonResult<NewsItem> getNoticeById(@PathVariable int id) {
        News news = newsService.findNewsById(id);
        if(news != null){
            NewsItem ni = news2Item(news);
            return ResultTool.success(ni);
        }
        return ResultTool.fail(ResultCode.PARAM_NOT_VALID);
    }

    /**
     * 获取新闻列表
     * @param page
     * @param size
     * @return
     */
    @GetMapping("/list")
    public JsonResult<Map> getNewsList(@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10")int size) {
        // System.out.println(page + "---" + size);
        // 读取新闻动态模块的新闻
        List<News> newsList = newsService.getNewsOfModul(2, page, size);
        // 将新闻转换成返回结构
        List<NewsItem> newsItems = newsList.stream().map(this::news2Item).collect(Collectors.toList());
        // 获取新闻总数
        int total = newsService.getNewsCountByModul(2);

        // 构建返回对象并返回
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("total", total);
        resultMap.put("list", newsItems);
        return ResultTool.success(resultMap);
    }

    /**
     * 根据编号删除新闻
     * @return
     */
    @PostMapping("/del/{id}")
    public JsonResult<Boolean> deleteNewsById(@PathVariable int id){
        boolean result = newsService.deleteNewsById(id);
        return ResultTool.success(result);
    }
    // 将新闻转换成返回格式
    private NewsItem news2Item(News news) {
        NewsItem ni = new NewsItem();// 构建返回消息
        ni.setAuthor(news.getAuthor().getName());
        ni.setAuthorId(news.getAuthor().getId());
        ni.setContent(news.getContent());
        ni.setId(news.getId());
        ni.setModul(news.getModul().getName());
        ni.setModuleId(news.getModul().getId());
        ni.setTitle(news.getTitle());
        ni.setUpdateTime(sdf.format(new Date(news.getUpdateTime())));
        return ni;
    }

}
